<?php

namespace Haozing\FastCore\Model;

use Haozing\FastCore\Context\UserContext;
use Haozing\FastCore\Utils\Auth\DataScopeType;
use Hyperf\Database\Model\Builder;
use function Hyperf\Config\config;

trait UserDataScopeModelTrait
{
    /**
     * 注册数据权限方法
     * @return void
     */
    private function registerDataScope(): void
    {
        // 部门数据，本人数据，所有数据
        // 使用通过user_id,数据创建者来限制查询数据，为什么不用部门id
        $model = $this;
        Builder::macro('userDataScope', function (?int $userId = null) use ($model) {
            if (!config('fastCore.data_scope_enabled')) {
                return $this;
            }
            //需要有登录用户信息
            $authUser = UserContext::get();
            $userId = is_null($userId) ? (int) $authUser->get('id'): $userId;
            if (empty($userId)) {
                throw new \Exception('Data Scope missing user_id');
            }
            //获取用户数据权限
            $dataScope = $authUser->get('data_scope');
            if (empty($dataScope)) {
                throw new \Exception('Data Scope missing data_scope');
            }

            //判断dataScope是否是数组，不是的话，则转成数组
            if (!is_array($dataScope)) {
                $dataScope = [$dataScope];
            }

            //获取用户权限数据
            $dataScopeData = $authUser->get('data_scope_data');
            //如果是平台用户，则直接返回
            $isAdmin = $authUser->get('is_admin');
            if ($isAdmin) {
                return $this;
            }

            //todo 先只做根据创建者查询权限
            if (!in_array($model->getDataScopeCreatedField(), $model->getFillable())) {
                return $this;
            }
            $createdIds = [];
            $deptIds = [];
            foreach ($dataScope as $scope) {
                switch ($scope) {
                    case DataScopeType::ALL_SCOPE:
                        // 拥有所有权限，跳出所有循环
                        break;
                    case DataScopeType::DEPT_SCOPE:
                        //如果根据创建者id查询，则获取创建者id
                        $createdIds[] = $dataScopeData[$scope] ?? [];
                        break;
                    case DataScopeType::SELF_SCOPE:
                        //本人数据
                        $createdIds[] = $userId;
                        break;
                    case DataScopeType::CUSTOM_SCOPE_ID:
                        //根据部门id查询
                        //先看是否配置了部门id
                        if (in_array($model->getDataScopeDeptIdField(), $model->getFillable())) {
                            $deptIds[] = $dataScopeData[$scope] ?? [];
                        }
                        break;
                }
            }

            if (!empty($createdIds)) {
                $this->whereIn($model->getDataScopeCreatedField(), $createdIds);
            }
            if (!empty($deptIds)) {
                $this->whereIn($model->getDataScopeDeptIdField(), $deptIds);
            }
            return $this;
        });
    }
}